import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { gql, useQuery } from '@apollo/client';

import Loading from '@kuiper-components/loading';
import Echarts from '@kuiper-components/echarts';

import EmptyData from '../../../../components/empty/EmptyData';
import EmptyPie from '../../../../components/empty/EmptyPie';
import Progress from '../../../../components/Progress';
import { percent } from '../../../../../common/formatter';
import ChartTitle from '../../../../components/ChartTitle';
import s from './style.module.css';

const numFormat = function (num) {
	try {
		return new Intl.NumberFormat('en-US').format(num);
	} catch {
		return num.toLocaleString('en-US');
	}
};

function VulCategory({
	className,
	jobId,
	resultNumbers,
	dateRange,
	detectTime,
	type,
}) {
	const palette = window.kuiper?.app?.palette || [];
	let res = [];
	let sum = 0;
	if (resultNumbers.length > 0) {
		sum = resultNumbers.length;
		const typeObj = {};
		resultNumbers.map(e => {
			if (typeObj[e.category]) {
				typeObj[e.category] += 1;
			} else {
				typeObj[e.category] = 1;
			}
		});
		res = Object.entries(typeObj)
			.map(item => {
				return { name: item[0], value: item[1] };
			})
			.sort((a, b) => b.value - a.value);
	}

	const option = {
		tooltip: {
			trigger: 'item',
			formatter({ name, percent, value }) {
				return `<div style="display:flex;padding:0.5rem">
				<div style="color: #2B2C32;padding-right: 0.25rem">${name}:</div>
				<div style="color: #2B2C32;padding-right: 0.25rem">${value}</div>
				<div style="color: #2B2C32">(${percent}%)</div>
			</div>`;
			},
			backgroundColor: '#fff',
			textStyle: {
				color: '#696969',
				fontSize: 12,
			},
		},
		legend: {
			show: false,
			orient: 'vertical',
			right: 20,
			icon: 'circle',
		},
		series: [
			{
				center: ['50%', '50%'],
				name: '漏洞占比',
				type: 'pie',
				radius: [100, 132],
				avoidLabelOverlap: false,
				hoverOffset: 5,
				label: {
					show: true,
					position: 'center',
					formatter: [
						`{normal|漏洞类型总数\n\n}`,
						`{highlight|${res?.length || 0}}`,
					].join(''),
					rich: {
						normal: {
							fontSize: 14,
							color: '#696C78',
						},
						highlight: {
							color: '#2B2C32',
							fontSize: 18,
						},
					},
				},
				emphasis: {
					label: {
						show: true,
						fontSize: 14,
						formatter: [
							`{normal|漏洞类型总数\n\n}`,
							`{highlight|${res?.length || 0}}`,
						].join(''),
						rich: {
							normal: {
								fontSize: 14,
								color: '#696C78',
							},
							highlight: {
								color: '#2B2C32',
								fontSize: 18,
							},
						},
					},
				},
				labelLine: {
					show: false,
				},
			},
		],
	};

	option.series[0].data = res;

	return (
		<div className={cn(className, s.vulCategory)}>
			<div className={s.left}>
				<ChartTitle className={s.title}>漏洞类型分布</ChartTitle>
				{res.length > 0 ? (
					<Echarts
						className={s.chart}
						option={option}
						key={JSON.stringify(dateRange)}
					/>
				) : (
					<div className={s.emptyContainer}>
						<EmptyPie
							className={s.empty}
							textContent={
								<div className={s.emptyContent}>
									<div className={s.text}>漏洞类型总数</div>
									<div className={s.num}>0</div>
								</div>
							}
						/>
					</div>
				)}
			</div>
			<div className={s.right}>
				<ChartTitle className={s.title}>漏洞统计TOP10</ChartTitle>
				<div className={s.tableWapper}>
					<div className={s.tableContainer}>
						<table className={cn(s.table, 'tableFormat')}>
							<thead>
								<tr className={s.head}>
									<th>漏洞名称</th>
									{type === 'host' && <th>漏洞类型</th>}
									<th>发现次数</th>
								</tr>
							</thead>
							<tbody>
								{res.map((item, index) => (
									<tr key={item.name} className={s.row}>
										<td className={s.name}>{item.name}</td>
										<td className={s.value}>
											<Progress
												percent={percent(item.value / sum)}
												className={s.progress}
												fillColor={`${
													index < 3
														? palette[index]
														: palette[palette.length - 1]
												}`}
											/>
											<span>{numFormat(item.value)}</span>
										</td>
									</tr>
								))}
							</tbody>
						</table>
						{res.length === 0 && <EmptyData className={s.emptyTable} />}
					</div>
				</div>
			</div>
		</div>
	);
}

VulCategory.propTypes = {
	className: PropTypes.string,
	jobId: PropTypes.string,
	resultNumbers: PropTypes.arrayOf(
		PropTypes.shape({
			warnCount: PropTypes.number,
			highWarnCount: PropTypes.number,
			mediumWarnCount: PropTypes.number,
			lowWarnCount: PropTypes.number,
			datetime: PropTypes.date,
		})
	),
	dateRange: PropTypes.shape({
		startTime: PropTypes.date,
		endTime: PropTypes.date,
	}),
	detectTime: PropTypes.string,
	type: PropTypes.string,
};
VulCategory.defaultProps = {
	className: '',
};

export default VulCategory;
